import re
import os
from collections import namedtuple
from itertools import groupby
import shutil

ImageInfo = namedtuple('ImageInfo', 'full file num')

src_dir = r'D:\dl\baidu_images'
des_dir = os.path.join(src_dir, 'renamed')
os.makedirs(des_dir, exist_ok=True)

# regstr = r'(.+?_)(\d{8,})(_.+)'
regstr = r'(.+?_.+?_.+?_.+?_)(\d+)(_.+)'


def replace_mid_nums(full, num):
    # print(full)
    return re.sub(regstr, r'\g<1>' + str(num).zfill(6) + r'\g<3>', full)


def extract_imageinfo(full, file):
    m = re.search(regstr, file)
    if m:
        return ImageInfo(full, file, m.group(2))
    else:
        print(f'{full} not valid file name !!!!!!!!!!!!!!!!!!!!!!!!')


if __name__ == "__main__":
    all_image_infos = []
    for f in os.listdir(src_dir):
        full = os.path.join(src_dir, f)
        image_info = extract_imageinfo(full, f)
        if image_info:
            all_image_infos.append(image_info)
    group_index = 0
    for num, g in groupby(all_image_infos, lambda x: x.num):
        # print(num)
        images = list(g)
        group_index += 1
        for img in images:
            des_file = replace_mid_nums(img.file, group_index)
            print(des_file)
            des_full = os.path.join(des_dir, des_file)
            if os.path.isfile(des_full):
                continue
            shutil.copy(img.full, des_full)
            print(f'copied {img.full} to {des_dir}')
    print('end')
